﻿#region Using

using System.Linq;

using GameCommon.ComponentInterfaces;
using GameCommon.Components;

using Menu.Components;
using Menu.XmlEntities;

using Container = Menu.Components.Container;

#endregion

namespace Menu.Common
{
    internal static class ComponentLoader
    {
        public static ComponentCollection GetComponentCollection(XmlScreen screen)
        {
            var collection = new ComponentCollection();

            foreach (var container in screen.Containers)
            {
                collection.AddRange(container.GetComponent());
            }

            StackComponents(collection);

            return collection;
        }

        private static void StackComponents(ComponentCollection components)
        {
            foreach (var container in components.OfType<Container>())
            {
                StackComponents(components, container);
            }
        }

        private static void StackComponents(ComponentCollection components, Container container)
        {
            IStackable previous = null;
            var componentBases = components.OfType<IStackable>();

            foreach (var component in componentBases.Where(x => x.Parent == container))
            {
                if (!component.Stackable)
                {
                    continue;
                }

                if (previous == null)
                {
                    previous = component;
                    continue;
                }

                component.Dimension.Position.Y = previous.Dimension.Position.Y + previous.Dimension.Size.Height;

                if (component is Text)
                {
                    EvaluateLineHeight(component as Text);
                }

                previous = component;
            }
        }

        private static void EvaluateLineHeight(Text component)
        {
            if (component == null || component.LineHeight == null)
            {
                return;
            }

            var height = component.LineHeight;

            if (height <= component.Dimension.Height)
            {
                return;
            }

            var diff = (height.Value - component.Dimension.Height) / 2;
            component.Dimension.Height = height.Value;
            component.Dimension.Position.Y += diff;
        }
    }
}